package com.moli.lumpSugar.gateway.filter;

import cn.hutool.core.collection.CollectionUtil;
import com.moli.lumpSugar.common.cache.user.UserCache;
import com.moli.lumpSugar.common.domain.enums.BlackTypeEnum;
import com.moli.lumpSugar.common.exception.HttpErrorEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;
import java.util.Set;

/**
 * @program: LumpSugarChatMicroservice
 * @description: 黑名单验证过滤器
 * @author: zhangjt
 * @create: 2024-11-27 15:18
 **/
@Component
public class BlackUserGlobalFilter implements GlobalFilter, Ordered {
    public static final String HEADER_AUTHORIZATION = "Authorization";
    public static final String AUTHORIZATION_SCAN = "Bearer ";
    public static final String UID = "uid";
    public static final int TOKEN_EXPIRE_DAY = 3;
    @Autowired
    private UserCache userCache;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 从请求头获取token
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 异步获取黑名单数据
        return userCache.getBlackListAsync()
                .flatMap(blackList -> {
                    // 检查用户是否在黑名单中
                    if (isBlackUser(request.getHeaders().get(UID), blackList.get(BlackTypeEnum.UID.getType()))) {
                        // 如果是黑名单用户，返回拒绝访问的响应
                        response.setRawStatusCode(HttpErrorEnum.ACCESS_DENIED.getErrorCode());
                        return response.setComplete();
                    }
                    // 否则继续执行过滤器链
                    return chain.filter(exchange);
                });
    }

    private Boolean isBlackUser(Object target, Set<String> blackList) {
        if (Objects.isNull(target) || CollectionUtil.isEmpty(blackList)) {
            return false;
        }
        return blackList.contains(target.toString());
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
